//
//  HomeHeadView.swift
//  ManBetX
//
//  Created by Cocoa on 2020/4/20.
//  Copyright © 2020 Fullen. All rights reserved.
//

import UIKit

// 首页HeadView

typealias HomeBannerClickBlock = (_ data:[String:Any]) -> Void
typealias HomeRecommendButtonClickBlock = (_ Index:Int) -> Void

class HomeHeadView: UICollectionReusableView,FSPagerViewDataSource,FSPagerViewDelegate{

    var bannerView = UIView()// 轮播图背景 View
    var recommendGameView = UIView()// 推荐游戏背景 View
    var allGameTitleView = UIView()// 全部游戏背景 titleView
    var allGameCategoryView = UIView()// 全部游戏标题 View
    var recommendTopLeftButton = UIButton.init()// 推荐游戏 - 左上
    var underMaintenanceTopLeftImageView = UIImageView.init()// 维护中 - 左上
    var recommendTopRightButton = UIButton.init()//推荐游戏 - 右上
    var underMaintenanceTopRightmageView = UIImageView.init()// 维护中 - 右上
    var recommendBottomLeftButton = UIButton.init()//推荐游戏 - 左下
    var underMaintenanceBottomLeftmageView = UIImageView.init()// 维护中 - 左下
    var recommendBottomRightButton = UIButton.init()//推荐游戏 - 右下
    var underMaintenanceBottomRightmageView = UIImageView.init()// 维护中 - 右下

    var pagerView: FSPagerView = FSPagerView.init(frame: .zero)// 轮播图
    var pageControl: FSPageControl = FSPageControl.init(frame: .zero)
    var homeBannerClickBlock: HomeBannerClickBlock?
    var homeRecommendButtonClickBlock: HomeRecommendButtonClickBlock?
    
    var dataArray: [[String:Any]] = NSMutableArray.init() as! [[String : Any]]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configureUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configureUI(){
        self.backgroundColor = UIColor.clear
        self.configureBannerView()
        self.configureRecommendGameView()
        self.configureAllGameTitleView()
        self.configureAllGameCategoryView()
    }
    
    // 配置数据
    func configureDataSource(_ dataArray: NSMutableArray){
        self.dataArray = dataArray as! [[String : Any]]
        self.pageControl.numberOfPages = self.dataArray.count
        self.pageControl.currentPage = self.pagerView.currentIndex
        self.pagerView.reloadData()
        
    }
//MARK: Banner背景父视图 -- 高度218
    // 配置 BannerView
    func configureBannerView (){
        
        self.bannerView.backgroundColor = UIColor.clear
        self.addSubview(self.bannerView)
        self.bannerView.snp.makeConstraints { (make) in
            make.top.equalTo(kNavigationBarHeight)
            make.left.right.equalToSuperview()
            make.height.equalTo(208.0)
        }
        
        self.pagerView = FSPagerView.init(frame: CGRect.init(x: 0, y: 15, width: self.bounds.size.width, height: 180.0))
        self.pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        self.pagerView.itemSize = CGSize.zero
        self.pagerView.interitemSpacing = 10 //间距
        self.pagerView.automaticSlidingInterval = 5 //间隔时间
        self.pagerView.isInfinite = true //循环滚动
        self.pagerView.dataSource = self
        self.pagerView.delegate = self
        self.pagerView.transformer = FSPagerViewTransformer(type:.linear)
        // FSPagerView 的 minimumScale 内部为作者自己自定义，修改minimumScale的同时记得修改下面注释的地方
        // 全局搜索【return pagerView.itemSize.width * -self.minimumScale * 0.05】
        self.pagerView.transformer?.minimumScale = 0.92
        
        self.pagerView.transformer?.minimumAlpha = 1.0
        let transform = CGAffineTransform(scaleX: 1 - 0.117, y: 1)
        self.pagerView.itemSize = self.pagerView.frame.size.applying(transform)
        self.pagerView.decelerationDistance = FSPagerView.automaticDistance
        
        self.bannerView.addSubview(self.pagerView)
//        self.pagerView.snp.makeConstraints{(make) in
//            make.top.equalTo(15.0)
//            make.bottom.equalTo(-13.0)
//            make.left.right.equalToSuperview()
//        }
        
        self.pageControl = FSPageControl.init(frame: self.bounds)
        self.pageControl.numberOfPages = self.dataArray.count
        self.pageControl.contentHorizontalAlignment = .right
        self.pageControl.hidesForSinglePage = true
        self.pageControl.contentHorizontalAlignment = .center
        self.pageControl.interitemSpacing = 10
        self.pageControl.currentPage = 0
        self.pageControl.setFillColor(HexRGBAlpha(0xffc569, 1), for: .selected)
        self.pageControl.setImage(UIImage(named:"icon_pageControl_nol"), for: .normal)
        self.pageControl.setImage(UIImage(named:"icon_pageControl_sel"), for: .selected)
        self.bannerView.addSubview(self.pageControl)
        self.pageControl.snp.makeConstraints{(make) in
            make.width.equalToSuperview()
            make.height.equalTo(20)
            make.bottom.equalTo(self.pagerView.snp.bottom).offset(5)
         }
        
    }
    
//MARK: 推荐游戏背景父视图 -- 高度311
    // 配置 RecommendGameView
    func configureRecommendGameView (){
        // 背景View
        self.recommendGameView.backgroundColor = UIColor.white
        self.recommendGameView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 305.0)
        // 设置圆角
        self.recommendGameView.setCornerWithCorners([UIRectCorner.topLeft,UIRectCorner.topRight], cornerRadii: CGSize.init(width: 8, height: 8), bounds: self.recommendGameView.frame)
        // 设置阴影
        self.recommendGameView.setViewShadowRadius(3.0, shadowColor: UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.2), shadowOpacity: -2)
        self.addSubview(self.recommendGameView)
        // 标题
        let titleLabel = self.customGameTitleLabel("推荐游戏")
        self.recommendGameView.addSubview(titleLabel)
        // 标题下的线
        let titleLineImageView = UIImageView.init(image: UIImage.init(named: "home_icon_gameTitleLineImage"))
        self.recommendGameView.addSubview(titleLineImageView)
        
        self.recommendTopLeftButton = self.customGameButton()
        self.recommendTopLeftButton.addTarget(self, action: #selector(topLeftButtonClick), for: .touchUpInside)
        self.recommendTopRightButton = self.customGameButton()
        self.recommendTopRightButton.addTarget(self, action: #selector(topRightButtonClick), for: .touchUpInside)
        self.recommendBottomLeftButton = self.customGameButton()
        self.recommendBottomLeftButton.addTarget(self, action: #selector(bottomLeftButtonClick), for: .touchUpInside)
        self.recommendBottomRightButton = self.customGameButton()
        self.recommendBottomRightButton.addTarget(self, action: #selector(bottomRightButtonClick), for: .touchUpInside)
        
        self.recommendGameView.addSubview(self.recommendTopLeftButton)
        self.recommendGameView.addSubview(self.recommendTopRightButton)
        self.recommendGameView.addSubview(self.recommendBottomLeftButton)
        self.recommendGameView.addSubview(self.recommendBottomRightButton)
        
        self.underMaintenanceTopLeftImageView = self.customGameImageView()
        self.recommendTopLeftButton.addSubview(self.underMaintenanceTopLeftImageView)
        self.underMaintenanceTopRightmageView = self.customGameImageView()
        self.recommendTopRightButton.addSubview(self.underMaintenanceTopRightmageView)
        self.underMaintenanceBottomLeftmageView = self.customGameImageView()
        self.recommendBottomLeftButton.addSubview(self.underMaintenanceBottomLeftmageView)
        self.underMaintenanceBottomRightmageView = self.customGameImageView()
        self.recommendBottomRightButton.addSubview(self.underMaintenanceBottomRightmageView)
        
        self.recommendGameView.snp.makeConstraints { (make) in
            make.top.equalTo(kNavigationBarHeight + 208.0)
            make.left.right.equalToSuperview()
            make.height.equalTo(302.0)
        }
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(10.0)
            make.left.equalTo(10.0)
            make.width.equalTo(70.0)
            make.height.equalTo(20.0)
        }
        titleLineImageView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(-1)
            make.left.equalTo(titleLabel.snp.left).offset(30.0)
            make.width.equalTo(32.0)
            make.height.equalTo(3.0)
        }
        let leftRightMargin: CGFloat = 8.0
        let spaceMargin: CGFloat = 14.0
        let buttonWidth: CGFloat = (kScreenWidth - leftRightMargin * 2 - spaceMargin)/2
        let buttonHeight: CGFloat = 111
        
        self.recommendTopLeftButton.snp.makeConstraints { (make) in
            make.top.equalTo(titleLineImageView.snp.bottom).offset(15)
            make.left.equalTo(leftRightMargin)
            make.width.equalTo(buttonWidth)
            make.height.equalTo(buttonHeight)
        }
        self.recommendTopRightButton.snp.makeConstraints { (make) in
            make.top.equalTo(self.recommendTopLeftButton.snp.top)
            make.left.equalTo(self.recommendTopLeftButton.snp.right).offset(spaceMargin)
            make.width.equalTo(buttonWidth)
            make.height.equalTo(buttonHeight)
        }
        self.recommendBottomLeftButton.snp.makeConstraints { (make) in
            make.top.equalTo(self.recommendTopLeftButton.snp.bottom).offset(spaceMargin)
            make.left.equalTo(leftRightMargin)
            make.width.equalTo(buttonWidth)
            make.height.equalTo(buttonHeight)
        }
        self.recommendBottomRightButton.snp.makeConstraints { (make) in
            make.top.equalTo(self.recommendTopLeftButton.snp.bottom).offset(spaceMargin)
            make.left.equalTo(self.recommendBottomLeftButton.snp.right).offset(spaceMargin)
            make.width.equalTo(buttonWidth)
            make.height.equalTo(buttonHeight)
        }
        
        self.underMaintenanceTopLeftImageView.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
            make.width.equalTo(77)
            make.height.equalTo(60)
        }
        self.underMaintenanceTopRightmageView.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
            make.width.equalTo(77)
            make.height.equalTo(60)
        }
        self.underMaintenanceBottomLeftmageView.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
            make.width.equalTo(77)
            make.height.equalTo(60)
        }
        self.underMaintenanceBottomRightmageView.snp.makeConstraints { (make) in
            make.top.right.equalToSuperview()
            make.width.equalTo(77)
            make.height.equalTo(60)
        }
    }
    
    // 配置 推荐游戏
    func configureRecommendGameData(_ dataArray: NSMutableArray) {
        
        for index in 0..<dataArray.count {
            
            let viewModel = dataArray.object(at: index) as? HomeSegmentViewModel
            if viewModel != nil {
                if index == 0 {
                    self.recommendTopLeftButton.sd_setBackgroundImage(with: URL(string: viewModel!.imgNameIOS), for: .normal, completed: nil)
                    self.underMaintenanceTopLeftImageView.isHidden = !viewModel!.isUnderMaintenance
                }else if index == 1 {
                    self.recommendTopRightButton.sd_setBackgroundImage(with: URL(string: viewModel!.imgNameIOS), for: .normal, completed: nil)
                    self.underMaintenanceTopRightmageView.isHidden = !viewModel!.isUnderMaintenance
                }else if index == 2 {
                    self.recommendBottomLeftButton.sd_setBackgroundImage(with: URL(string: viewModel!.imgNameIOS), for: .normal, completed: nil)
                    self.underMaintenanceBottomLeftmageView.isHidden = !viewModel!.isUnderMaintenance
                }else if index == 3 {
                    self.recommendBottomRightButton.sd_setBackgroundImage(with: URL(string: viewModel!.imgNameIOS), for: .normal, completed: nil)
                    self.underMaintenanceBottomRightmageView.isHidden = !viewModel!.isUnderMaintenance
                }
            }
        }
    }
    
//MARK: 全部游戏背景父视图 -- 高度37
    // 配置全部游戏标题View
    func configureAllGameTitleView() {
        // 背景View
        self.allGameTitleView.backgroundColor = UIColor.white
        self.allGameTitleView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 33.0)
        // 设置圆角
        self.allGameTitleView.setCornerWithCorners([UIRectCorner.topLeft,UIRectCorner.topRight], cornerRadii: CGSize.init(width: 8, height: 8), bounds: self.allGameTitleView.frame)
        self.addSubview(self.allGameTitleView)
        
        self.allGameTitleView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(33.0)
            make.bottom.equalTo(-52.0)
        }
        
        // 标题
        let titleLabel = self.customGameTitleLabel("全部游戏")
        self.allGameTitleView.addSubview(titleLabel)
        // 标题下的线
        let titleLineImageView = UIImageView.init(image: UIImage.init(named: "home_icon_gameTitleLineImage"))
        self.allGameTitleView.addSubview(titleLineImageView)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(10.0)
            make.left.equalTo(10.0)
            make.width.equalTo(70.0)
            make.height.equalTo(20.0)
        }
        titleLineImageView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(-1)
            make.left.equalTo(titleLabel.snp.left).offset(30.0)
            make.width.equalTo(32.0)
            make.height.equalTo(3.0)
        }
    }
    // 配置CategoryView
    func configureAllGameCategoryView() {
        
        self.allGameCategoryView.backgroundColor = UIColor.green
        self.allGameCategoryView.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 52.0)
        self.addSubview(self.allGameCategoryView)
        
        self.allGameCategoryView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.left.right.equalToSuperview()
            make.height.equalTo(52.0)
        }
    }
    
    // 便捷创建 Button
    func customGameButton() -> UIButton {
        
        let gameButton = UIButton.init(type: .custom)
        gameButton.layer.masksToBounds = true
        gameButton.layer.cornerRadius = 8
        gameButton.setBackgroundImage(UIImage.init(named: "icon_newhome_game_zwt_bg_max"), for: .normal)
        gameButton.contentMode = UIView.ContentMode.scaleAspectFill
        return gameButton
    }
    
    // 便捷创建 ImageView
    func customGameImageView() -> UIImageView {
        
        let underMaintenanceImageView = UIImageView.init()
        underMaintenanceImageView.image = UIImage.init(named: "icon_home_whz")
        underMaintenanceImageView.contentMode = UIView.ContentMode.scaleAspectFill
        underMaintenanceImageView.isHidden = true
        return underMaintenanceImageView
    }
    
    
    // 标题
    func customGameTitleLabel(_ title: NSString) -> UILabel {

        let titleLabel = UILabel.init()
        titleLabel.font = UIFont.init(name: "PingFangSC-Medium", size: 16.0)
        titleLabel.textColor = UIColor.init("333333")
        titleLabel.text = title as String
        return titleLabel
    }
    
    // MARK: -- clickEvent
    @objc func topLeftButtonClick() {
        let index = 0
        if self.homeRecommendButtonClickBlock != nil {
            self.homeRecommendButtonClickBlock!(index)
        }
        print("topLeftButtonClick")
    }
    @objc func topRightButtonClick() {
        let index = 1
        if self.homeRecommendButtonClickBlock != nil {
            self.homeRecommendButtonClickBlock!(index)
        }
        print("topRightButtonClick")
    }
    @objc func bottomLeftButtonClick() {
        let index = 2
        if self.homeRecommendButtonClickBlock != nil {
            self.homeRecommendButtonClickBlock!(index)
        }
        print("bottomLeftButtonClick")
    }
    @objc func bottomRightButtonClick() {
        let index = 3
        if self.homeRecommendButtonClickBlock != nil {
            self.homeRecommendButtonClickBlock!(index)
        }
        print("bottomRightButtonClick")
    }
 
    
    
//MARK: --Banner

    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        
        let banner = self.dataArray[index]
        cell.imageView?.sd_setImage(with: URL.init(string: banner["imgUrl"] as? String ?? ""), placeholderImage: imageNamed("img_default_banner"), options: .refreshCached, completed: nil);

        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
        cell.masksToBounds = true
        cell.cornerRadius = 8.0
        return cell
    }
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.dataArray.count
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        let bannerData = self.dataArray[index]
        print("\(bannerData)")
        self.pageControl.currentPage = index
        if self.homeBannerClickBlock != nil{
              self.homeBannerClickBlock!(bannerData)
        }
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex // Or Use KVO with property "currentIndex"
    }
}
